$(function() {

	var DOMAIN_PATH = '/apps-deploy',
		APPS_LIST_URL = DOMAIN_PATH + '/apps/list',
		APP_BY_NAME_URL = DOMAIN_PATH + '/apps/name/',
		APP_ADD_URL = DOMAIN_PATH + '/apps/action/add',
		APP_DEPLOY_BY_BAME_URL = DOMAIN_PATH + '/apps/action/deploy/name/',
		APP_RECORD_BY_NAME_URL = DOMAIN_PATH + '/apps/record/name/',
		APP_SHOW_URL = DOMAIN_PATH + '/applications/';

	var mainPanel = $('#panel-container');

	var appAddModal = $('#addAppModal'),
		confirmModal = $('#confirmModal');

	var applicationStatus = {
		'UNPUBLISHED': 'info',
		'PUBLISHED': 'success'
	};

	mainPanel.height($(window).height() - 120);
	$(window).resize(function() {
		mainPanel.height(Math.max($(this).height() - 120, 300));
	});

	$.get(APPS_LIST_URL, function(list) {
		$.each(list, function(index, application) {
			custructAppShowPanel(application);
		});
	});

	appAddModal.on('show.bs.modal', function() {
		$(this).find('form')[0].reset();
		$(this).find('button:last').prop('disabled', true);
		var alertDiv = $(this).find('.alet');
		if (alertDiv) {
			alertDiv.alert('close');
		}
	});

	appAddModal.on('keyup', function() {
		var disableSaveBtn = false,
			appAddForm = $(this).find('form');
		appAddForm.find('input').each(function() {
			if ($(this).val().length == 0) {
				disableSaveBtn = true;
			}
		});
		if (appAddForm.find('textarea').val().length == 0) {
			disableSaveBtn = true;
		}
		$(this).find('button:last').prop('disabled', disableSaveBtn);
	});

	appAddModal.find('button:last').on('click', function() {
		var appAddForm = appAddModal.find('form');
	    var postParam = {
	        name: appAddForm.find('input:eq(0)').val(),
	        description: appAddForm.find('textarea').val(),
	        url: appAddForm.find('input:eq(1)').val(),
	        status: 'UNPUBLISHED'
	    };
	    $.post(APP_ADD_URL, postParam, function(result) {
	        if (result.succeeded) {
	        	appAddModal.modal('hide');
	        	custructAppShowPanel(postParam);
	        } else {
	        	appAddForm.before(custructAlert('danger', '<strong>Error: </strong>' + result.message));
	        }
	    });
	});

	confirmModal.on('show.bs.modal', function(e) {
		$(this).find('.modal-body')
			   .html('You sure you want to delete <b><em>'
						+ $(e.relatedTarget).siblings().text() + '</em></b> application ?');
		var alertDiv = $(this).find('.alet');
		if (alertDiv) {
			alertDiv.alert('close');
		}
	});

	confirmModal.find('button:last').on('click', function() {
		var appName = confirmModal.find('em').text();
		console.log(appName);
	    $.ajax({
	        url: APP_BY_NAME_URL + appName,
	        type: 'DELETE'
	    }).done(function(result) {
	        if (result.succeeded) {
	        	confirmModal.modal('hide');
	        	$('.row .panel').each(function() {
	        		if ($(this).find('.panel-title').text() == appName) {
	        			console.log('appname' + appName);
	        			$(this).parent().remove();
	        		}
	        	});
	        } else {
	        	confirmModal.find('.modal-body').prepend(custructAlert('danger', '<strong>Error: </strong>' + result.message));
	        }
	    });
	});

	function custructAlert(alertType, message) {
		return '<div class="alert alert-' + alertType + ' alert-dismissible">' + 
					'<button class="close" data-dismiss="alert" aria-label="Close">' + 
						'<span aria-hidden="true">&times;</span></button>' + message + 
				'</div>';
	}

	function custructAppShowPanel(application) {
		$('.row a[href="#addAppModal"]')
			.parent()
			.before(
				'<div class="col-sm-6 col-md-4 col-lg-3">' + 
					'<div class="panel panel-' + applicationStatus[application.status] + '">' +
						'<div class="panel-heading">' + 
							'<a href="' + APP_SHOW_URL + application.name + '" class="panel-title">' + application.name + '</a>' +
							'<a href="#confirmModal" class="pull-right glyphicon glyphicon-remove" data-toggle="modal"></a>' + 
						'</div>' +
						'<div class="panel-body">' + application.description + '</div>' +
						'<div class="panel-footer">' + 
							'<a href="' + application.url + '">' + application.url + '</a>' +
						'</div>' + 
					'</div>' + 
				'</div>' );
	}

});